import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//查询
public class dome2 {
    public static void main(String[] args) throws SQLException {
        //1.创建datasource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl( "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.连接数据库
        Connection connection = dataSource.getConnection();
        //3.构造sql
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,2);

        //4.执行sql (和前面有所不同)
        //ResultSet 表示查询的结果集(临时表)   此处需要针对表遍历来获取数据
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合
        //通过resultSet.next()方法来获取(临时表)每一行数据,如果获取表中最后一行时,再执行 next 就返回false 循环结束
        while (resultSet.next()){
            //进入循环,就会针对当前行来操作处理
             int id = resultSet.getInt("id");
             String name = resultSet.getString("name");
            System.out.println("id = "+ id +" , name= "+ name);
        }
        //6.释放
        resultSet.close();
        statement.close();
        connection.close();



    }
}
